
<template>
  <el-dialog
    width="27%"
    title="上传图片"
    :visible.sync="innerVisible"
    append-to-body
    @close="imgClose"
  >
    <el-row>
      <el-upload
        ref="upload"
        action="http://122.51.249.55:7005/admin/index/upload?mode=base64&type=image"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :headers="myToken"
        :auto-upload="false"
        :on-change="getFile"
        :http-request="upload"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-row>
    <el-row type="flex" justify="end" style="margin-top:60px">
      <el-button @click="imgClose">取消</el-button>
      <el-button type="primary" @click="clickUp">确定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { uploadImg } from '@/api/tagInfo'
export default {
  name: 'ImgUpload',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      innerVisible: false, // 上传图片弹出层
      myToken: { Authorization: null },
      file: {
        url: ''
      }
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  created() {
    this.myToken.Authorization = this.token
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getFile(file, fileList) { // 选取图片的时候把图片转成base64格式
      this.file = file
      this.getBase64(file.raw).then(res => {
        this.file.url = res
      })
    },
    getBase64(file) { // 将图片转成base64格式
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    async  upload() { // 上传图片
      const { data } = await uploadImg({ file: this.file.url, filename: this.file.name })
      this.$emit('uploadImg', data.url)
      this.$message.success('图片上传成功')
      this.imgClose()
    },
    clickUp() { // 触发上传
      this.upload()
    },
    imgClose() { // 上传图片弹窗关闭事件
      this.innerVisible = false
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style>

</style>
